<template>
	<el-main style="padding: 0px">
		<div class="plan-delay-view-container" v-loading="state.exportLoading">
			<!-- 计划筛选内容 -->
			<QueryForm :dropdown-data="state.dropdownData" :initial-query-params="state.queryParams" @query="handleQuery" @reset="handleReset" />

			<!-- 统计卡片 -->
			<StatisticsCards :delay-counts="state.delayCounts" :loading="state.exportLoading" :error="state.dataError" @retry="handleRetry" />

			<!-- 延期情况分析 -->
			<el-card class="plan-delay-tabs art-custom-card" shadow="hover">
				<template #header>
					<div class="card-header">
						<el-icon style="display: inline; vertical-align: middle"> <ele-DataAnalysis /> </el-icon>
						<span>延期情况分析</span>
						<div class="header-actions">
							<!-- <el-switch v-model="state.autoRefresh" @change="toggleAutoRefresh" active-text="自动刷新" inactive-text="手动刷新" size="small" style="margin-right: 10px" /> -->
							<!-- <el-button type="success" size="small" :icon="Download" @click="handleExport" title="导出数据"> 导出 </el-button> -->
							<el-button type="danger" size="small" :icon="Bell" :loading="state.notificationLoading" @click="handleSendNotifications" title="推送延期通知" v-auth="'plandelayview:sendNotification'"> 推送通知 </el-button>
							<el-button type="warning" size="small" :icon="Delete" @click="handleClearCache" title="清除缓存"> 清除缓存 </el-button>
							<el-button type="primary" size="small" :icon="Refresh" :loading="state.refreshLoading" @click="handleRefresh" title="刷新数据"> 刷新 </el-button>
						</div>
					</div>
				</template>
				<div class="analysis-charts">
					<!-- 区域延期情况总览 -->
					<div class="chart-section">
						<div class="section-header">
							<el-icon><ele-Location /></el-icon>
							<span>各区域延期情况</span>
							<span class="filter-info" v-if="state.queryParams.className"> (筛选分类: {{ getClassNameLabel(state.queryParams.className) }}) </span>
						</div>
						<div class="chart-container">
							<div ref="areaChartRef" style="width: 100%; height: 100%; min-height: 400px" v-loading="state.exportLoading"></div>
						</div>
					</div>

					<!-- 分类延期情况总览 -->
					<div class="chart-section">
						<div class="section-header">
							<el-icon><ele-Files /></el-icon>
							<span>各分类延期情况</span>
							<span class="filter-info" v-if="state.queryParams.workAreaId"> (筛选区域: {{ getWorkAreaLabel(state.queryParams.workAreaId) }}) </span>
						</div>
						<div class="chart-container">
							<div ref="categoryChartRef" style="width: 100%; height: 100%; min-height: 400px" v-loading="state.exportLoading"></div>
						</div>
					</div>
				</div>
			</el-card>

			<!-- 延期明细列表 -->
			<el-card class="plan-delay-detail art-custom-card" shadow="hover">
				<template #header>
					<div class="card-header">
						<el-icon style="display: inline; vertical-align: middle"> <ele-Document /> </el-icon>
						<span>延期明细列表</span>
					</div>
				</template>
				<DelayDetailTables :filter-params="state.queryParams" @loading-change="handleTableLoading" />
			</el-card>
		</div>

		<!-- 通知配置对话框 -->
		<NotificationConfigDialog
			v-model:visible="state.notificationConfigDialog.visible"
			:formData="state.notificationConfigDialog.formData"
			:preview="state.notificationConfigDialog.preview"
			:loading="state.notificationConfigDialog.loading"
			:previewLoading="state.notificationConfigDialog.previewLoading"
			:userOptions="state.notificationConfigDialog.userOptions"
			:roleOptions="state.notificationConfigDialog.roleOptions"
			:classNameOptions="state.dropdownData.className"
			:workAreaOptions="state.dropdownData.workAreaId"
			@preview="handlePreviewRecipients"
			@confirm="handleConfirmSendNotification"
		/>
	</el-main>
</template>

<script lang="ts" setup name="planDelayView">
import { ref, reactive, onMounted, computed, nextTick, watch, onUnmounted } from 'vue';
import { ElMessage, ElNotification, ElMessageBox } from 'element-plus';
import { Refresh, Download, Delete, Bell } from '@element-plus/icons-vue';
import { usePlanDelayViewApi, type PlanDelayStartInput, type PlanDelayAllInput } from '/@/api/plans/planDelayView';
import { usePlanTypeApi } from '/@/api/plans/planType';
import { getAPI } from '/@/utils/axios-utils';
import { SysOrgApi, SysUserApi, SysRoleApi } from '/@/api-services/api';
import { SysOrg } from '/@/api-services/models';
import { QueryForm, StatisticsCards, DelayDetailTables, NotificationConfigDialog } from './components';
import * as echarts from 'echarts';
import { signalR } from '/@/views/system/onlineUser/signalR';
import { auth } from '/@/utils/authFunction';

const planDelayViewApi = usePlanDelayViewApi();
const planTypeApi = usePlanTypeApi();
const sysUserApi = getAPI(SysUserApi);
const sysRoleApi = getAPI(SysRoleApi);

// ECharts DOM引用
const areaChartRef = ref<HTMLElement>();
const categoryChartRef = ref<HTMLElement>();

// ECharts实例
let areaChartInstance: echarts.ECharts | null = null;
let categoryChartInstance: echarts.ECharts | null = null;

// 防抖函数
const debounce = (func: Function, wait: number) => {
	let timeout: NodeJS.Timeout;
	return function executedFunction(...args: any[]) {
		const later = () => {
			clearTimeout(timeout);
			func(...args);
		};
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
	};
};

const state = reactive({
	exportLoading: false,
	refreshLoading: false,
	notificationLoading: false, // 通知推送加载状态
	autoRefresh: false, // 自动刷新开关
	autoRefreshInterval: 300000, // 自动刷新间隔（5分钟）
	delayCounts: {
		allPlanCount: 0,
		allActualCount: 0,
		delayPlanCount: 0,
		delayActualCount: 0,
		delayPlanRate: 0,
		delayActualRate: 0,
	},
	dropdownData: {
		className: [] as Array<{ value: number | null; label: string }>,
		workAreaId: [] as Array<{ value: number | null; label: string }>,
	},
	queryParams: {
		workTime: (() => {
			const now = new Date();
			return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
		})(),
		className: null as number | null,
		workAreaId: null as number | null,
		keyword: '',
		planStart: false, // 默认未完成
	},
	areaChartDataCache: null as any,
	categoryChartDataCache: null as any,
	dataError: false, // 用于统计卡片加载错误
	// 通知配置对话框
	notificationConfigDialog: {
		visible: false,
		loading: false,
		previewLoading: false,
		formData: {
			workTime: '',
			className: undefined as number | undefined,
			workAreaId: undefined as number | undefined,
			notificationType: 3,
			delayLevels: [4],
			recipientMode: 1,
			specificUserIds: [] as number[],
			specificRoleIds: [] as number[],
			includeSubordinates: false,
			customMessage: ''
		},
		preview: null as any, // 接收人预览数据
		userOptions: [] as Array<{ value: number; label: string; phone?: string; email?: string }>,
		roleOptions: [] as Array<{ value: number; label: string; code?: string }>
	}
});

// 自动刷新定时器
let autoRefreshTimer: NodeJS.Timeout | null = null;

// 根据筛选条件过滤区域数据
const filteredAreas = computed(() => {
	// 如果选择了特定区域，只显示该区域
	if (state.queryParams.workAreaId) {
		return state.dropdownData.workAreaId.filter((area) => area.value === state.queryParams.workAreaId);
	}
	// 如果没有选择区域，显示所有区域
	return state.dropdownData.workAreaId;
});

// 根据筛选条件过滤分类数据
const filteredCategories = computed(() => {
	// 如果选择了特定分类，只显示该分类
	if (state.queryParams.className) {
		return state.dropdownData.className.filter((category) => category.value === state.queryParams.className);
	}
	// 如果没有选择分类，显示所有分类
	return state.dropdownData.className;
});

// 获取分类名称
const getClassNameLabel = (classNameId: number | null) => {
	if (!classNameId) return '';
	const category = state.dropdownData.className.find((c) => c.value === classNameId);
	return category?.label || '';
};

// 获取区域名称
const getWorkAreaLabel = (workAreaId: number | null) => {
	if (!workAreaId) return '';
	const area = state.dropdownData.workAreaId.find((a) => a.value === workAreaId);
	return area?.label || '';
};

// 加载下拉数据
const loadDropdownData = async () => {
	// 分类
	const planTypeData = await planTypeApi.page({ page: 1, pageSize: 99999999 }).then((res) => res.data.result);
	state.dropdownData.className = planTypeData?.items?.map((item: any) => ({ value: item.id, label: item.name })) ?? [];
	// 区域
	const orgData = await getAPI(SysOrgApi)
		.apiSysOrgListGet(0)
		.then((res) => res.data.result);
	// 递归提取所有组织，然后过滤出作业区
	const extractAllOrgs = (orgs: SysOrg[]): SysOrg[] => {
		const result: SysOrg[] = [];
		orgs.forEach((org) => {
			result.push(org);
			if (org.children && org.children.length > 0) {
				result.push(...extractAllOrgs(org.children));
			}
		});
		return result;
	};
	
	// 过滤出名称包含"作业区"的组织
	const extractWorkAreas = (orgs: SysOrg[]): Array<{ value: number | null; label: string }> => {
		return orgs
			.filter(org => org.name && org.name.includes('作业区'))
			.map(org => ({
				value: org.id ?? null,
				label: org.name || ''
			}));
	};
	
	const allOrgs = extractAllOrgs(orgData || []);
	state.dropdownData.workAreaId = extractWorkAreas(allOrgs);
};

// 获取延期统计数据
const fetchDelayData = async () => {
	try {
		state.exportLoading = true;
		state.dataError = false; // 重置错误状态

		// 获取延期状态统计
    const rng = (() => {
        const rs = (state.queryParams as any).rangeStart;
        const re = (state.queryParams as any).rangeEnd;
        if (rs && re) return { rangeStart: rs, rangeEnd: re };
        // 兼容：从workTime推导
        const wt = state.queryParams.workTime;
        if (wt) {
            const [y, m] = wt.split('-').map((s) => parseInt(s, 10));
            if (y && m) {
                const target = new Date(y, m - 1, 1);
                const prev = new Date(y, m - 2, 1);
                const pad = (n: number) => String(n).padStart(2,'0');
                const fmt = (d: Date) => `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${String(d.getMilliseconds()).padStart(3,'0')}`;
                const start = new Date(prev.getFullYear(), prev.getMonth(), 26, 0,0,0,0);
                const end = new Date(target.getFullYear(), target.getMonth(), 25, 23,59,59,999);
                return { rangeStart: fmt(start), rangeEnd: fmt(end) };
            }
        }
        return {} as any;
    })();
    const statusParams: PlanDelayStartInput = {
        className: state.queryParams.className || undefined,
        workAreaId: state.queryParams.workAreaId || undefined,
        planStart: state.queryParams.planStart,
        ...rng,
    } as any;

		const statusRes = await planDelayViewApi.getPlanDelayStatus(statusParams);
		if (statusRes?.data?.result) {
			const result = statusRes.data.result;
			state.delayCounts = {
				allPlanCount: result.allPlanCount ?? 0,
				allActualCount: result.allActualCount ?? 0,
				delayPlanCount: result.delayPlanCount ?? 0,
				delayActualCount: result.delayActualCount ?? 0,
				delayPlanRate: result.delayPlanRate ?? 0,
				delayActualRate: result.delayActualRate ?? 0,
			};
		}

		// 获取图表数据
    const chartParams: PlanDelayAllInput = {
        className: state.queryParams.className || undefined,
        workAreaId: state.queryParams.workAreaId || undefined,
        planStart: state.queryParams.planStart,
        ...rng,
    } as any;

		console.log('图表API调用参数:', chartParams);
		const [areaRes, categoryRes] = await Promise.all([planDelayViewApi.getAreaDelayCharts(chartParams), planDelayViewApi.getClassDelayCharts(chartParams)]);

		if (areaRes?.data?.result) {
			state.areaChartDataCache = { ...areaRes.data.result };
			// 立即渲染区域图表
			nextTick(() => renderAreaChart());
		}

		if (categoryRes?.data?.result) {
			state.categoryChartDataCache = { ...categoryRes.data.result };
			// 立即渲染分类图表
			nextTick(() => renderCategoryChart());
		}
	} catch (error) {
		console.error('获取延期数据失败:', error);
		state.dataError = true;
		ElMessage.error('获取延期数据失败');
	} finally {
		state.exportLoading = false;
	}
};

// 初始化ECharts
const initCharts = () => {
	if (areaChartRef.value && !areaChartInstance) {
		areaChartInstance = echarts.init(areaChartRef.value);
	}
	if (categoryChartRef.value && !categoryChartInstance) {
		categoryChartInstance = echarts.init(categoryChartRef.value);
	}
	
	// 添加窗口大小调整监听
	window.addEventListener('resize', handleResize);
};

// 处理窗口大小调整
const handleResize = () => {
	areaChartInstance?.resize();
	categoryChartInstance?.resize();
};

// 渲染区域延期图表
const renderAreaChart = () => {
	// 如果图表实例不存在，先尝试初始化
	if (!areaChartInstance && areaChartRef.value) {
		areaChartInstance = echarts.init(areaChartRef.value);
	}
	
	if (!areaChartInstance || !state.areaChartDataCache) return;
	
	const data = state.areaChartDataCache;
	const option = {
		title: {
			text: '各区域延期情况',
			left: 'center',
			textStyle: { fontSize: 16, fontWeight: 'bold', color: '#303133' }
		},
		tooltip: {
			trigger: 'axis',
			axisPointer: { type: 'shadow' },
			formatter: (params: any) => {
				const dataIndex = params[0].dataIndex;
				return `
					<div style="padding: 8px;">
						<div style="font-weight: bold; margin-bottom: 8px;">${data.categories?.[dataIndex] || ''}</div>
						<div style="color: #409eff;">总计划数: ${data.totalCounts?.[dataIndex] || 0}</div>
						<div style="color: #f56c6c;">延期数量: ${data.delayCounts?.[dataIndex] || 0}</div>
						<div style="color: #e6a23c;">延期率: ${data.delayRates?.[dataIndex] || 0}%</div>
					</div>
				`;
			}
		},
		legend: {
			data: ['总计划数', '延期数量', '延期率'],
			top: 40,
			itemGap: 20
		},
		grid: { left: '3%', right: '4%', bottom: '8%', top: '20%', containLabel: true },
		xAxis: [{
			type: 'category',
			data: data.categories || [],
			axisTick: { alignWithLabel: true },
			axisLabel: { rotate: 0, interval: 0, fontSize: 12 }
		}],
		yAxis: [
			{ type: 'value', name: '数量', position: 'left', axisLabel: { formatter: '{value}' } },
			{ type: 'value', name: '延期率(%)', position: 'right', axisLabel: { formatter: '{value}%' } }
		],
		series: [
			{
				name: '总计划数',
				type: 'bar',
				yAxisIndex: 0,
				data: data.totalCounts || [],
				itemStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: '#409eff' }, { offset: 1, color: '#79bbff' }]) },
				barWidth: '25%'
			},
			{
				name: '延期数量',
				type: 'bar',
				yAxisIndex: 0,
				data: data.delayCounts || [],
				itemStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: '#f56c6c' }, { offset: 1, color: '#f89898' }]) },
				barWidth: '25%'
			},
			{
				name: '延期率',
				type: 'line',
				yAxisIndex: 1,
				data: data.delayRates || [],
				lineStyle: { color: '#e6a23c', width: 3 },
				itemStyle: { color: '#e6a23c' },
				symbol: 'circle',
				symbolSize: 8,
				smooth: true
			}
		],
		animation: true,
		animationDuration: 1000,
		animationEasing: 'cubicOut' as const
	};
	
	areaChartInstance.setOption(option, true);
};

// 渲染分类延期图表
const renderCategoryChart = () => {
	// 如果图表实例不存在，先尝试初始化
	if (!categoryChartInstance && categoryChartRef.value) {
		categoryChartInstance = echarts.init(categoryChartRef.value);
	}
	
	if (!categoryChartInstance || !state.categoryChartDataCache) return;
	
	const data = state.categoryChartDataCache;
	const pieData = (data.categories || []).map((category: string, index: number) => ({
		name: category,
		value: (data.delayCounts || [])[index] || 0,
		total: (data.totalCounts || [])[index] || 0,
		rate: (data.delayRates || [])[index] || 0
	}));
	
	const option = {
		title: {
			text: '各分类延期情况',
			left: 'center',
			textStyle: { fontSize: 16, fontWeight: 'bold', color: '#303133' }
		},
		tooltip: {
			trigger: 'item',
			formatter: (params: any) => {
				const data = params.data;
				return `
					<div style="padding: 8px;">
						<div style="font-weight: bold; margin-bottom: 8px;">${data.name}</div>
						<div style="color: #409eff;">总计划数: ${data.total}</div>
						<div style="color: #f56c6c;">延期数量: ${data.value}</div>
						<div style="color: #e6a23c;">延期率: ${data.rate}%</div>
						<div style="color: #909399;">占比: ${params.percent}%</div>
					</div>
				`;
			}
		},
		legend: {
			type: 'scroll',
			orient: 'horizontal',
			bottom: 10,
			data: data.categories || [],
			itemGap: 20,
			textStyle: { fontSize: 12 }
		},
		series: [{
			name: '延期分布',
			type: 'pie',
			radius: ['40%', '70%'],
			center: ['50%', '45%'],
			avoidLabelOverlap: false,
			itemStyle: { borderRadius: 8, borderColor: '#fff', borderWidth: 2 },
			label: {
				show: true,
				position: 'outside',
				formatter: (params: any) => `${params.name}\n${params.data.value}项\n${params.percent}%`,
				fontSize: 11,
				fontWeight: 'bold'
			},
			emphasis: {
				label: { show: true, fontSize: 14, fontWeight: 'bold' },
				itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0,0,0,0.5)' }
			},
			labelLine: { show: true, length: 15, length2: 20, smooth: 0.3 },
			data: pieData,
			animationType: 'scale',
			animationDelay: (idx: number) => Math.random() * 200,
			color: [
				new echarts.graphic.LinearGradient(0, 0, 1, 1, [{ offset: 0, color: '#667eea' }, { offset: 1, color: '#764ba2' }]),
				new echarts.graphic.LinearGradient(0, 0, 1, 1, [{ offset: 0, color: '#f093fb' }, { offset: 1, color: '#f5576c' }]),
				new echarts.graphic.LinearGradient(0, 0, 1, 1, [{ offset: 0, color: '#4facfe' }, { offset: 1, color: '#00f2fe' }]),
				new echarts.graphic.LinearGradient(0, 0, 1, 1, [{ offset: 0, color: '#43e97b' }, { offset: 1, color: '#38f9d7' }]),
				new echarts.graphic.LinearGradient(0, 0, 1, 1, [{ offset: 0, color: '#fa709a' }, { offset: 1, color: '#fee140' }]),
				new echarts.graphic.LinearGradient(0, 0, 1, 1, [{ offset: 0, color: '#a8edea' }, { offset: 1, color: '#fed6e3' }])
			]
		}]
	};
	
	categoryChartInstance.setOption(option, true);
};

// 监听数据变化并更新图表（备用机制）
watch(
	() => state.areaChartDataCache,
	(newData) => {
		if (newData) {
			nextTick(() => renderAreaChart());
		}
	},
	{ deep: true }
);

watch(
	() => state.categoryChartDataCache,
	(newData) => {
		if (newData) {
			nextTick(() => renderCategoryChart());
		}
	},
	{ deep: true }
);

onMounted(async () => {
    await loadDropdownData();

	// 初始化图表（延迟以确保DOM元素存在）
	await nextTick();
	initCharts();

    // 计算默认范围（26→25），用于未通过查询控件时的初始加载
    try {
        const wt = state.queryParams.workTime;
        if (wt) {
            const [y, m] = wt.split('-').map((s) => parseInt(s, 10));
            if (y && m) {
                const target = new Date(y, m - 1, 1);
                const prev = new Date(y, m - 2, 1);
                const pad = (n: number) => String(n).padStart(2,'0');
                const fmt = (d: Date) => `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${String(d.getMilliseconds()).padStart(3,'0')}`;
                (state.queryParams as any).rangeStart = fmt(new Date(prev.getFullYear(), prev.getMonth(), 26, 0,0,0,0));
                (state.queryParams as any).rangeEnd = fmt(new Date(target.getFullYear(), target.getMonth(), 25, 23,59,59,999));
            }
        }
    } catch {}

    // 获取延期数据
    await fetchDelayData();

	// 初始化SignalR延期通知监听
	initSignalRNotificationListener();

	// 只在有推送通知权限时才初始化通知配置对话框数据
	if (auth('plandelayview:sendNotification')) {
		await initUserOptions();
		await initRoleOptions();
	}
});

// 启动自动刷新
const startAutoRefresh = () => {
	if (autoRefreshTimer) {
		clearInterval(autoRefreshTimer);
	}

	if (state.autoRefresh) {
		autoRefreshTimer = setInterval(async () => {
			console.log('自动刷新延期数据...');
			await fetchDelayData();
		}, state.autoRefreshInterval);
	}
};

// 停止自动刷新
const stopAutoRefresh = () => {
	if (autoRefreshTimer) {
		clearInterval(autoRefreshTimer);
		autoRefreshTimer = null;
	}
};

// // 切换自动刷新状态
// const toggleAutoRefresh = () => {
// 	state.autoRefresh = !state.autoRefresh;
// 	if (state.autoRefresh) {
// 		startAutoRefresh();
// 		ElMessage.success('已开启自动刷新（5分钟间隔）');
// 	} else {
// 		stopAutoRefresh();
// 		ElMessage.info('已关闭自动刷新');
// 	}
// };

// 监听自动刷新状态变化
watch(
	() => state.autoRefresh,
	(newVal) => {
		if (newVal) {
			startAutoRefresh();
		} else {
			stopAutoRefresh();
		}
	}
);

// 组件卸载时移除定时器
onUnmounted(() => {
	stopAutoRefresh();
	
	// 销毁ECharts实例
	if (areaChartInstance) {
		areaChartInstance.dispose();
		areaChartInstance = null;
	}
	if (categoryChartInstance) {
		categoryChartInstance.dispose();
		categoryChartInstance = null;
	}
	
	// 移除窗口大小调整监听
	window.removeEventListener('resize', handleResize);

	// 移除SignalR延期通知监听
	removeSignalRNotificationListener();
});

const handleQuery = async (params: any) => {
	// 更新查询参数
	Object.assign(state.queryParams, params);

	// 使用防抖的延期数据获取
	debouncedFetchDelayData();
};

// 防抖版本的延期数据获取函数
const debouncedFetchDelayData = debounce(async () => {
	await fetchDelayData();
}, 300);

const handleReset = async () => {
	// 重置查询参数
	state.queryParams.className = null;
	state.queryParams.workAreaId = null;
	state.queryParams.keyword = '';
	state.queryParams.planStart = false; // 保持默认未完成

	// 获取延期数据
	await fetchDelayData();
};

// 手动刷新数据
const handleRefresh = async () => {
	try {
		state.refreshLoading = true;
		// 清空缓存，强制重新获取数据
		state.areaChartDataCache = null;
		state.categoryChartDataCache = null;

		// 重新获取延期数据
		await fetchDelayData();

		ElMessage.success('数据刷新成功');
	} catch (error) {
		console.error('刷新数据失败:', error);
		ElMessage.error('刷新数据失败');
	} finally {
		state.refreshLoading = false;
	}
};

// 数据导出
// const handleExport = async () => {
// 	try {
// 		state.exportLoading = true;

// 		// 准备导出参数
// 		const params = {
// 			workTime: state.queryParams.workTime,
// 			className: state.queryParams.className,
// 			workAreaId: state.queryParams.workAreaId,
// 			keyword: state.queryParams.keyword,
// 			planStart: state.queryParams.planStart,
// 		};

// 		ElMessage.info('导出功能待实现');
// 	} catch (error) {
// 		console.error('导出数据失败:', error);
// 		ElMessage.error('导出数据失败');
// 	} finally {
// 		state.exportLoading = false;
// 	}
// };

// 清除缓存
const handleClearCache = async () => {
	try {
		// 清空本地缓存
		state.areaChartDataCache = null;
		state.categoryChartDataCache = null;

		// 重新获取数据
		await fetchDelayData();

		ElMessage.success('缓存清除成功');
	} catch (error) {
		console.error('清除缓存失败:', error);
		ElMessage.error('清除缓存失败');
	}
};

// 重试获取统计数据
const handleRetry = async () => {
	try {
		state.dataError = false; // 重置错误状态
		await fetchDelayData(); // 重新尝试获取数据
	} catch (error) {
		state.dataError = true; // 设置错误状态
		console.error('重试获取数据失败:', error);
	}
};

// 处理表格加载状态
const handleTableLoading = (loading: boolean) => {
	// 可以在这里处理表格的加载状态
};

// 推送延期通知
const handleSendNotifications = async () => {
	// 权限检查
	if (!auth('plandelayview:sendNotification')) {
		ElMessage.error('您没有推送通知的权限');
		return;
	}

	try {
		// 初始化选项（如果尚未加载）
		if (state.notificationConfigDialog.userOptions.length === 0) {
			await initUserOptions();
		}
		if (state.notificationConfigDialog.roleOptions.length === 0) {
			await initRoleOptions();
		}

		// 显示高级通知配置对话框
		state.notificationConfigDialog.visible = true;
    state.notificationConfigDialog.formData = {
        rangeStart: (state.queryParams as any).rangeStart,
        rangeEnd: (state.queryParams as any).rangeEnd,
        className: state.queryParams.className || undefined,
        workAreaId: state.queryParams.workAreaId || undefined,
        notificationType: 3, // 推送全部延期（开工+完工）
        delayLevels: [4], // 推送所有等级的延期
        recipientMode: 1, // 默认自动按权限
			specificUserIds: [],
			specificRoleIds: [],
			includeSubordinates: false,
			customMessage: ''
		};
		// 清空之前的预览
		state.notificationConfigDialog.preview = null;
	} catch (error) {
		console.error('打开通知配置对话框失败:', error);
		ElMessage.error('打开通知配置失败');
	}
};

// 初始化用户选项
const initUserOptions = async () => {
	try {
		const response = await sysUserApi.apiSysUserPagePost({
			page: 1,
			pageSize: 100,
			descStr: 'createTime'
		});
		
		if (response.data?.result?.items) {
			state.notificationConfigDialog.userOptions = response.data.result.items.map((user: any) => ({
				value: user.id,
				label: user.realName || user.account,
				phone: user.phone,
				email: user.email
			}));
		}
	} catch (error) {
		console.error('获取用户列表失败:', error);
	}
};

// 初始化角色选项
const initRoleOptions = async () => {
	try {
		const response = await sysRoleApi.apiSysRoleListGet();
		if (response?.data?.result) {
			state.notificationConfigDialog.roleOptions = response.data.result.map((role: any) => ({
				value: role.id,
				label: role.name,
				code: role.code
			}));
		}
	} catch (error) {
		console.error('获取角色列表失败:', error);
	}
};

// 预览通知接收人
const handlePreviewRecipients = async () => {
	try {
		state.notificationConfigDialog.previewLoading = true;
		const response = await planDelayViewApi.previewNotificationRecipients(state.notificationConfigDialog.formData);
		
		if (response?.data?.result) {
			state.notificationConfigDialog.preview = response.data.result;
		} else {
			ElMessage.warning('预览接收人失败');
		}
	} catch (error) {
		console.error('预览接收人失败:', error);
		ElMessage.error('预览接收人失败');
	} finally {
		state.notificationConfigDialog.previewLoading = false;
	}
};

// 确认发送通知
const handleConfirmSendNotification = async () => {
	try {
		state.notificationConfigDialog.loading = true;
		
		const response = await planDelayViewApi.sendDelayNotifications(state.notificationConfigDialog.formData);
		console.log('延期通知推送响应:', response);

		if (response?.data?.result?.success) {
			const result = response.data.result;
			ElMessage.success({
				message: `推送成功！共推送 ${result.totalDelayCount} 项延期给 ${result.notifiedUserCount} 位用户`,
				duration: 5000,
				showClose: true
			});

			// 关闭对话框
			state.notificationConfigDialog.visible = false;

			// 显示推送详情
			if (result.details && result.details.length > 0) {
				const detailsHtml = result.details.map((detail: any) => 
					`<div style="margin-bottom: 8px;">
						<strong>${detail.workAreaName}</strong>: ${detail.delayItemCount}项延期 
						(严重:${detail.severeDelayCount} 中等:${detail.mediumDelayCount} 轻微:${detail.lightDelayCount})
						→ 推送给 ${detail.notifiedUserNames.slice(0, 3).join(', ')}${detail.notifiedUserNames.length > 3 ? ` 等${detail.notifiedUserNames.length}人` : ''}
					</div>`
				).join('');

				ElMessageBox.alert(detailsHtml, '推送详情', {
					dangerouslyUseHTMLString: true,
					confirmButtonText: '知道了'
				});
			}
		} else {
			ElMessage.warning(response?.data?.result?.errorMessage || '推送失败，请稍后重试');
		}
		
	} catch (error) {
		if (error !== 'cancel') { // 用户取消时不显示错误
			console.error('推送延期通知失败:', error);
			ElMessage.error('推送延期通知失败，请检查网络连接');
		}
	} finally {
		state.notificationConfigDialog.loading = false;
	}
};

// 初始化SignalR延期通知监听
const initSignalRNotificationListener = () => {
	// 监听延期通知消息
	signalR.on('ReceiveMessage', handleDelayNotificationMessage);
	console.log('SignalR延期通知监听已初始化');
};

// 移除SignalR延期通知监听
const removeSignalRNotificationListener = () => {
	// 移除延期通知消息监听
	signalR.off('ReceiveMessage', handleDelayNotificationMessage);
	console.log('SignalR延期通知监听已移除');
};

// 处理接收到的延期通知消息
const handleDelayNotificationMessage = (message: any) => {
	console.log('收到SignalR延期通知消息:', message);
	
	// 通过消息标题或内容识别延期警报（因为MessageType现在是Warning枚举）
	const isDelayAlert = message.Title?.includes('延期警报') || 
	                    message.Message?.includes('延期') && 
	                    (message.Message?.includes('严重') || message.Message?.includes('中等') || message.Message?.includes('轻微'));
	
	// 只处理延期警报类型的消息
	if (isDelayAlert) {
		ElNotification({
			title: message.Title || '延期警报',
			message: message.Message,
			type: 'warning',
			duration: 0, // 不自动关闭
			showClose: true,
			position: 'top-right',
			onClick: () => {
				// 点击通知时可以跳转到对应的延期详情
				console.log('点击了延期通知');
			}
		});

		// 如果当前在延期看板页面，可以刷新数据
		if (window.location.pathname.includes('plandelayview')) {
			ElMessage({
				message: '收到新的延期警报，数据将自动刷新',
				type: 'info',
				duration: 3000
			});
			
			// 延迟刷新数据，避免过于频繁
			setTimeout(() => {
				handleRefresh();
			}, 2000);
		}
	}
};
</script>

<style lang="scss" scoped>
.plan-delay-view-container {
	width: 100%;
	padding: 4px;
	min-height: 100vh;
}

.art-custom-card {
	margin-bottom: 8px;
	border: 1px solid var(--el-border-color-light);
	border-radius: 4px;
	transition: all 0.3s ease;
	&:hover {
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	}
}

.plan-delay-tabs .el-card__header,
.plan-delay-detail .el-card__header {
	border-radius: 4px 4px 0 0;
}

.plan-delay-tabs {
	width: 100%;

	.el-card__header {
		background: var(--el-bg-color);
		color: var(--el-text-color-primary);
		border-bottom: 1px solid var(--el-border-color-light);
		padding: 15px 20px;
	}

	.card-header {
		font-size: 14px;
		font-weight: 500;
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.header-actions {
		margin-left: auto;
	}

	.analysis-charts {
		padding: 20px;

		.chart-section {
			margin-bottom: 30px;

			&:last-child {
				margin-bottom: 0;
			}

			.section-header {
				display: flex;
				align-items: center;
				gap: 8px;
				margin-bottom: 15px;
				font-size: 16px;
				font-weight: 600;
				color: var(--el-text-color-primary);

				.filter-info {
					font-size: 12px;
					opacity: 0.8;
					font-weight: normal;
					margin-left: 8px;
				}
			}

			.chart-container {
				height: 400px;
				border: 1px solid var(--el-border-color-light);
				border-radius: 8px;
				overflow: hidden;
			}
		}
	}
}

.plan-delay-detail {
	width: 100%;

	.el-card__header {
		background: var(--el-bg-color);
		color: var(--el-text-color-primary);
		border-bottom: 1px solid var(--el-border-color-light);
		padding: 15px 20px;
	}

	.card-header {
		font-size: 14px;
		font-weight: 500;
		display: flex;
		align-items: center;
		gap: 8px;
	}
}

:deep(.el-card) {
	border-radius: 4px !important;
}
:deep(.el-card__header) {
	border-radius: 4px 4px 0 0 !important;
}

// 响应式设计
@media (max-width: 768px) {
	.plan-delay-view-container {
		padding: 4px;
	}
	.art-custom-card {
		margin-bottom: 8px;
	}

	.plan-delay-tabs {
		.el-card__header {
			padding: 12px 15px;
		}

		.card-header {
			flex-direction: column;
			align-items: flex-start;
			gap: 5px;
		}

		.header-actions {
			width: 100%;
			display: flex;
			justify-content: flex-end;
		}

		.analysis-charts {
			padding: 15px;

			.chart-section {
				margin-bottom: 20px;

				.section-header {
					font-size: 14px;
					margin-bottom: 10px;

					.filter-info {
						font-size: 11px;
					}
				}

				.chart-container {
					height: 300px;
				}
			}
		}
	}

	.plan-delay-detail {
		.el-card__header {
			padding: 12px 15px;
		}
	}
}
</style>
